package com.lvyq.service.impl;

import com.lvyq.common.BagConstant;
import com.lvyq.common.ShopTypeConstant;
import com.lvyq.common.WearHouseConstant;
import com.lvyq.common.pasture.HabitationTypeEnum;
import com.lvyq.common.pasture.PastureGrowUpType;
import com.lvyq.model.bag.MyBag;
import com.lvyq.model.bag.MyWareHouse;
import com.lvyq.model.pasture.MyPasture;
import com.lvyq.model.pasture.PastureFeeding;
import com.lvyq.model.pasture.PastureGoodsInfo;
import com.lvyq.model.receive.ReceiveMsg;
import com.lvyq.model.shop.ShopGoods;
import com.lvyq.model.user.User;
import com.lvyq.repository.MyBagRepository;
import com.lvyq.repository.MyWareHouseRepository;
import com.lvyq.repository.UserRepository;
import com.lvyq.repository.pasture.MyPastureRepository;
import com.lvyq.repository.pasture.PastureFeedingRepository;
import com.lvyq.repository.pasture.PastureGoodsInfoRepository;
import com.lvyq.service.PastureService;
import com.lvyq.util.DateUtil;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: weg
 * @description: 牧场相关
 * @author: lvyq
 * @create: 2023-04-28 10:14
 **/


@Service
public class PastureServiceImpl implements PastureService {

    @Resource
    private MyPastureRepository myPastureRepository;

    @Resource
    private PastureFeedingRepository pastureFeedingRepository;


    @Resource
    private PastureGoodsInfoRepository pastureGoodsInfoRepository;

    @Resource
    private MyBagRepository myBagRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MyWareHouseRepository myWareHouseRepository;


    /**
    * @Description: 小窝牧场
     * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/28 10:16
    */
    
    @Override
    public String orderReply(String replyContent, ReceiveMsg receiveMsg) {
        //小窝牧场查看
        if (receiveMsg.getContent().equals("小窝牧场")){
            replyContent = pastureInfo(replyContent,receiveMsg);
        }

        //购买牧场
        if (receiveMsg.getContent().equals("购买牧场")){
            replyContent=buyPasture(replyContent,receiveMsg);
        }

        //牧场背包
        if (receiveMsg.getContent().equals("牧场背包")){
            replyContent=pastureBag(replyContent,receiveMsg);
        }

        //牧场商店  //查看目前不能购买的幼仔
        if (receiveMsg.getContent().equals("牧场商店") ||receiveMsg.getContent().equals("查看目前不能购买的幼仔")){
            replyContent=pastuerShop(replyContent,receiveMsg);
        }

        //饲养
        if (receiveMsg.getContent().startsWith("饲养#") ||receiveMsg.getContent().startsWith("饲养$")){
            replyContent=feedingReply(replyContent,receiveMsg);
        }
        //赶产
        if (receiveMsg.getContent().startsWith("赶产$")){
            replyContent=expeReply(replyContent,receiveMsg);
        }
        //牧场仓库
        if (receiveMsg.getContent().equals("牧场仓库")){
            replyContent=wearHouseReply(replyContent,receiveMsg);
        }

        //加锁
        if (receiveMsg.getContent().startsWith("加锁$")){
            replyContent=lockReply(replyContent,receiveMsg);
        }

        //解锁
        if (receiveMsg.getContent().startsWith("解锁$")){
            replyContent=unLockReply(replyContent,receiveMsg);
        }
        //卖出$
        if (receiveMsg.getContent().startsWith("卖出$")){
            replyContent=sellReply(replyContent,receiveMsg);
        }
        //全部卖出
        if (receiveMsg.getContent().equals("全部卖出")){
            replyContent=sellAllReply(replyContent,receiveMsg);
        }
        //收获
        if (receiveMsg.getContent().startsWith("收获$")){
            replyContent=getGoodsReply(replyContent,receiveMsg);
        }
        //一键收获
        if (receiveMsg.getContent().equals("一键收获")){
            replyContent=getGoodsAllReply(replyContent,receiveMsg);
        }
        //一键收获
        if (receiveMsg.getContent().equals("一键赶产")){
            replyContent=expeAllReply(replyContent,receiveMsg);
        }
        //添加牧草
        if (receiveMsg.getContent().equals("添加牧草")){
            replyContent=addMuCaoReply(replyContent,receiveMsg);
        }
        return replyContent;
    }

    /**
     * 添加牧草
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String addMuCaoReply(String replyContent, ReceiveMsg receiveMsg) {
        MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(receiveMsg.getFromUserName(),"牧草");
        if (wareHouse!=null){
                MyPasture myPasture= myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
                Integer mucao=myPasture.getMucao();
                Integer addMuCao=0;
                if (wareHouse.getNum()>(1000-mucao)){
                    addMuCao=1000-mucao;
                    wareHouse.setNum(wareHouse.getNum()-addMuCao);
                    mongoTemplate.save(wareHouse);
                }else {
                    addMuCao=wareHouse.getNum();
                    myWareHouseRepository.deleteById(wareHouse.getId());
                }
                myPasture.setMucao(myPasture.getMucao()+addMuCao);
                mongoTemplate.save(myPasture);
                replyContent=replyContent.replace("{num}",addMuCao.toString());
        }else {
            replyContent="添加牧草失败，牧草不存在,可通过农场采集获得";
        }
        return replyContent;
    }

    /***
     * 一键赶产
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String expeAllReply(String replyContent, ReceiveMsg receiveMsg) {
        String info="";
        //获取生产期状态的数据
        Query query = new Query().addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()))
                .addCriteria(Criteria.where("type").is(PastureGrowUpType.SCQ.getType()));
        List<PastureFeeding> feedingList = mongoTemplate.find(query,PastureFeeding.class);
        //获取当前动物对应的赶产物品;
        StringBuffer buffer = new StringBuffer();
        Integer totalExp=0;
        if (feedingList.size()>0){
            for (PastureFeeding feeding:feedingList){
                PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(feeding.getGoodsName());
                //更新为待产期
                feeding.setType(PastureGrowUpType.DCQ.getType());
                feeding.setNextProduceTime(System.currentTimeMillis()+goodsInfo.getProduceTime()*1000*60*60);
                feeding.setTypeName(PastureGrowUpType.DCQ.getName());
                feeding.setNestTypeName(PastureGrowUpType.SCQ.getName());
                mongoTemplate.save(feeding);
                //更新仓库
                MyWareHouse myWareHouse = myWareHouseRepository.findByOpenIdAndGoodsNameAndType(receiveMsg.getFromUserName(),goodsInfo.getProductName(),WearHouseConstant.MC);
                if (myWareHouse!=null){
                    myWareHouse.setNum(myWareHouse.getNum()+goodsInfo.getYieldNum());
                }else {
                    myWareHouse =  new MyWareHouse();
                    myWareHouse.setGoodsName(goodsInfo.getProductName());
                    myWareHouse.setNum(goodsInfo.getYieldNum());
                    myWareHouse.setType(WearHouseConstant.MC);
                    myWareHouse.setOpenId(receiveMsg.getFromUserName());
                    myWareHouse.setState(0);
                    myWareHouse.setUnit(goodsInfo.getProductUnit());
                    myWareHouse.setPrice(goodsInfo.getCubPrice());
                }
                mongoTemplate.save(myWareHouse);
                buffer.append(goodsInfo.getProductName()+"x"+goodsInfo.getYieldNum()+"\n");
                totalExp=goodsInfo.getProductHarvestExp()+goodsInfo.getProductionExp()+totalExp;
            }

        }else {
            replyContent="赶产失败,当前没有可赶产的动物";
            return replyContent;
        }
        //更新牧场
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        myPasture.setJingYan(myPasture.getJingYan()+totalExp);
        Integer nextLevelExp = (myPasture.getLevel()+1)*200;
        if (myPasture.getJingYan()>nextLevelExp){
            myPasture.setJingYan(nextLevelExp-myPasture.getJingYan());
            myPasture.setLevel(myPasture.getLevel()+1);
        }
        mongoTemplate.save(myPasture);
        info=buffer.toString();
        replyContent= replyContent.replace("{info}",info).replace("{jingyan}",totalExp.toString());
        return replyContent;
    }

    /**
     *一键收获
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String getGoodsAllReply(String replyContent, ReceiveMsg receiveMsg) {
        List<PastureFeeding> feedingList = new ArrayList<>();
        Query query = new Query().addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()))
                .addCriteria(Criteria.where("type").is(PastureGrowUpType.SHQ.getType()));
        feedingList=mongoTemplate.find(query,PastureFeeding.class);
        if (feedingList.size()>0){
                Integer totalExp=0;
                StringBuffer buffer = new StringBuffer();
                for (PastureFeeding feeding:feedingList){
                    PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(feeding.getGoodsName());
                    MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(feeding.getOpenId(),feeding.getGoodsName());
                    if (wareHouse!=null){
                        wareHouse.setNum(wareHouse.getNum()+1);
                    }else {
                        wareHouse=new MyWareHouse();
                        wareHouse.setGoodsName(feeding.getGoodsName());
                        wareHouse.setPrice(goodsInfo.getSellingRate());
                        wareHouse.setUnit("个");
                        wareHouse.setNum(1);
                        wareHouse.setType(WearHouseConstant.MC);
                        wareHouse.setState(0);
                        wareHouse.setOpenId(receiveMsg.getFromUserName());
                    }
                    totalExp=totalExp+goodsInfo.getHarvestExp();
                    buffer.append(wareHouse.getGoodsName()+"x1\n");
                    mongoTemplate.save(wareHouse);
                }
            //更新牧场
            MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
            myPasture.setJingYan(myPasture.getJingYan()+totalExp);
            Integer nextLevelExp = (myPasture.getLevel()+1)*200;
            if (myPasture.getJingYan()>nextLevelExp){
                myPasture.setJingYan(nextLevelExp-myPasture.getJingYan());
                myPasture.setLevel(myPasture.getLevel()+1);
            }
            mongoTemplate.save(myPasture);
            mongoTemplate.remove(query,PastureFeeding.class);
            replyContent=replyContent.replace("{info}",buffer.toString()).replace("{jingyan}",totalExp.toString());
        }else {
            replyContent="收获失败,暂未可收获动物";
        }
        return replyContent;
    }

    /**
     * 收获
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String getGoodsReply(String replyContent, ReceiveMsg receiveMsg) {
        String goodsName= receiveMsg.getContent().split("\\$")[1];
        PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(goodsName);
        List<PastureFeeding> pastureFeedings = pastureFeedingRepository.findByOpenIdAndTypeAndGoodsName(receiveMsg.getFromUserName(),PastureGrowUpType.SHQ.getType(),goodsName);
        if (pastureFeedings.size()>0){
                PastureFeeding feeding = pastureFeedings.get(0);
                MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(feeding.getOpenId(),feeding.getGoodsName());
                if (wareHouse!=null){
                        wareHouse.setNum(wareHouse.getNum()+1);
                }else {
                    wareHouse=new MyWareHouse();
                    wareHouse.setGoodsName(goodsName);
                    wareHouse.setPrice(goodsInfo.getSellingRate());
                    wareHouse.setUnit("个");
                    wareHouse.setNum(1);
                    wareHouse.setType(WearHouseConstant.MC);
                    wareHouse.setState(0);
                    wareHouse.setOpenId(receiveMsg.getFromUserName());
                }
                pastureFeedingRepository.delete(feeding);
                mongoTemplate.save(wareHouse);
                //更新牧场
            MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
            myPasture.setJingYan(myPasture.getJingYan()+goodsInfo.getHarvestExp());
            Integer nextLevelExp = (myPasture.getLevel()+1)*200;
            if (myPasture.getJingYan()>nextLevelExp){
                myPasture.setJingYan(nextLevelExp-myPasture.getJingYan());
                myPasture.setLevel(myPasture.getLevel()+1);
            }
            mongoTemplate.save(myPasture);
                replyContent=replyContent.replace("{info}",goodsName+"x1").replace("{jingyan}",goodsInfo.getHarvestExp().toString());
        }else {
            replyContent="收获失败,动物未到收获期";
        }
        return replyContent;
    }

    /** 
    * @Description: 全部卖出
     * @param replyContent
   * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/5/10 22:51
    */
    
    private String sellAllReply(String replyContent, ReceiveMsg receiveMsg) {
        //获取牧场数据
        Query query = new Query().addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()))
                .addCriteria(Criteria.where("type").is(WearHouseConstant.MC))
                .addCriteria(Criteria.where("state").is(0));
        List<MyWareHouse> wareHouses = mongoTemplate.find(query,MyWareHouse.class);
        if (wareHouses.size()>0){
            Integer totalPrice=0;
            for (MyWareHouse wareHouse:wareHouses){
                Integer price = wareHouse.getPrice()*wareHouse.getNum();
                totalPrice=totalPrice+price;
            }
            User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
            user.setJinbi(user.getJinbi()+totalPrice);
            mongoTemplate.save(user);
            mongoTemplate.remove(query,MyWareHouse.class);
            replyContent=replyContent.replace("{jinbi}",totalPrice.toString());
        }else {
            replyContent="卖出失败,物品不存在";
        }
        return replyContent;
    }

    /** 
    * @Description: 卖出
     * @param replyContent
 * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/5/10 22:42
    */
    
    private String sellReply(String replyContent, ReceiveMsg receiveMsg) {
        String goodsName= receiveMsg.getContent().split("\\$")[1];
        MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(receiveMsg.getFromUserName(),goodsName);
        if (wareHouse!=null){
            if (wareHouse.getState()==1){
                replyContent="卖出失败,物品已上锁";
                return replyContent;
            }
            Integer num = wareHouse.getNum();
            Integer price = wareHouse.getPrice();
            Integer totalPrice=num*price;
            User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
            user.setJinbi(user.getJinbi()+totalPrice);
            mongoTemplate.save(user);
            Query query = new Query();
            query.addCriteria(Criteria.where("goodsName").is(goodsName));
            mongoTemplate.remove(query,MyWareHouse.class);
            replyContent=replyContent.replace("{jinbi}",totalPrice.toString());
        }else {
            replyContent="卖出失败,物品不存在";
        }
        return replyContent;
    }

    /** 
    * @Description: 解锁
     * @param replyContent
 * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/5/10 22:41
    */
    
    private String unLockReply(String replyContent, ReceiveMsg receiveMsg) {
        String goodsName= receiveMsg.getContent().split("\\$")[1];
        MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(receiveMsg.getFromUserName(),goodsName);
        if (wareHouse!=null){
            wareHouse.setState(0);
            mongoTemplate.save(wareHouse);
        }else {
            replyContent="解锁失败,物品不存在";
        }
        return replyContent;
    }

    /** 
    * @Description: 加锁
     * @param replyContent
 * @param receiveMsg
    * @return: {@link String}
    * @Author: lvyq
    * @Date: 2023/5/10 22:41
    */
    
    private String lockReply(String replyContent, ReceiveMsg receiveMsg) {
        String goodsName= receiveMsg.getContent().split("\\$")[1];
        MyWareHouse wareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(receiveMsg.getFromUserName(),goodsName);
        if (wareHouse!=null){
            wareHouse.setState(1);
            mongoTemplate.save(wareHouse);
        }else {
            replyContent="加锁失败,物品不存在";
        }
        return replyContent;
    }

    /**
     * 牧场仓库
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String wearHouseReply(String replyContent, ReceiveMsg receiveMsg) {
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        //未开启牧场，开启牧场操作
        if (myPasture==null){
            replyContent="您还未拥有牧场，请【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=购买牧场\">购买牧场</a>】,购买牧场将花费1000\uD83D\uDCB0金币";
            return replyContent;
        }
        String info="您的仓库空空如也";
        List<MyWareHouse> houseList= myWareHouseRepository.findByOpenIdAndType(receiveMsg.getFromUserName(),WearHouseConstant.MC);
        Integer jinbi=0;
        if (houseList.size()>0){
            StringBuffer buffer = new StringBuffer();
            int index=0;
            String lock="  【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent={do}${goodsName}\">{do}</a>】";
            String sell="【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=卖出${goodsName}\">卖出</a>】";
            for (MyWareHouse house:houseList){
                index=index+1;
                String str = house.getGoodsName()+"("+house.getPrice()+"金币/"+house.getUnit()+"):"+house.getNum()+house.getUnit()+"\n";
                if (house.getState()==0){
                    jinbi=jinbi+(house.getNum()*house.getPrice());
                    //未上锁
                    buffer.append(index+")"+str+lock.replace("{do}","加锁").replace("{goodsName}",house.getGoodsName())+sell.replace("{goodsName}",house.getGoodsName())+"\n");
                }else {
                    //上锁
                    buffer.append(index+")【锁】"+str+lock.replace("{do}","解锁").replace("{goodsName}",house.getGoodsName())+"\n");
                }

            }
            info =buffer.toString();
        }
        replyContent=replyContent.replace("{goods}",info).replace("{jinbi}",jinbi.toString());
        return replyContent;
    }

    /**
     * 赶产操作
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String expeReply(String replyContent, ReceiveMsg receiveMsg) {
        String info="";
        String goodsName= receiveMsg.getContent().split("\\$")[1];
        //获取生产期状态的数据
        List<PastureFeeding> feedingList = pastureFeedingRepository.findByOpenIdAndTypeAndGoodsName(receiveMsg.getFromUserName(),PastureGrowUpType.SCQ.getType(),goodsName);
        //获取当前动物对应的赶产物品;
        PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(goodsName);
        if (feedingList.size()>0){
            PastureFeeding feeding = feedingList.get(0);
            //更新为待产期
            feeding.setType(PastureGrowUpType.DCQ.getType());
            feeding.setNextProduceTime(System.currentTimeMillis()+goodsInfo.getProduceTime()*1000*60*60);
            feeding.setTypeName(PastureGrowUpType.DCQ.getName());
            feeding.setNestTypeName(PastureGrowUpType.SCQ.getName());
            mongoTemplate.save(feeding);
        }else {
            replyContent="赶产失败,当前没有可赶产的动物";
            return replyContent;
        }
        //更新牧场
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        Integer getExp=goodsInfo.getProductHarvestExp()+goodsInfo.getProductionExp();
        myPasture.setJingYan(goodsInfo.getProductionExp()+getExp);
        Integer nextLevelExp = (myPasture.getLevel()+1)*200;
        if (myPasture.getJingYan()>nextLevelExp){
            myPasture.setJingYan(nextLevelExp-myPasture.getJingYan());
            myPasture.setLevel(myPasture.getLevel()+1);

        }
            mongoTemplate.save(myPasture);
        //更新仓库
        MyWareHouse myWareHouse = myWareHouseRepository.findByOpenIdAndGoodsNameAndType(receiveMsg.getFromUserName(),goodsInfo.getProductName(),WearHouseConstant.MC);
        if (myWareHouse!=null){
            myWareHouse.setNum(myWareHouse.getNum()+goodsInfo.getYieldNum());
        }else {
            myWareHouse =  new MyWareHouse();
            myWareHouse.setGoodsName(goodsInfo.getProductName());
            myWareHouse.setNum(goodsInfo.getYieldNum());
            myWareHouse.setType(WearHouseConstant.MC);
            myWareHouse.setOpenId(receiveMsg.getFromUserName());
            myWareHouse.setState(0);
            myWareHouse.setUnit(goodsInfo.getProductUnit());
            myWareHouse.setPrice(goodsInfo.getCubPrice());
        }
        mongoTemplate.save(myWareHouse);
        info=goodsInfo.getYieldNum()+goodsInfo.getProductUnit()+goodsInfo.getProductName();
        replyContent= replyContent.replace("{info}",info).replace("{jingyan}",getExp.toString());
        return replyContent;
    }

    /**
     * 饲养 -每次饲养一个
     * @param replyContent
     * @param receiveMsg
     * @return
     */
    private String feedingReply(String replyContent, ReceiveMsg receiveMsg) {
        String content = receiveMsg.getContent();
        Integer goodsNum=1;
        String goodsName= content.split("\\$")[1];
        //根据名称获取饲养动物相关属性
        PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(goodsName);
        if (goodsInfo==null){
            replyContent="饲养失败,请正确使用物品";
            return replyContent;
        }
        MyBag myBag = myBagRepository.findByGoodsNameAndOpenId(goodsName,receiveMsg.getFromUserName());
        if (myBag==null){
            replyContent="饲养失败,背包中不存在【"+goodsName+"】";
            return replyContent;
        }
        if (myBag.getNum()<goodsNum){
            replyContent="饲养失败,【"+goodsName+"】数量不足";
            return replyContent;
        }
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        if (myPasture==null){
            replyContent="饲养失败,您还未拥有牧场,请【购买牧场】";
            return replyContent;
        }
        //根据居住地类型查询
        List<PastureFeeding> feedingList = pastureFeedingRepository.findByOpenIdAndHabitationType(receiveMsg.getFromUserName(),goodsInfo.getHabitationType());
        List<PastureFeeding> pslist = pastureFeedingRepository.findByOpenIdAndHabitationType(receiveMsg.getFromUserName(),HabitationTypeEnum.PS.getType());
        List<PastureFeeding> wslist = pastureFeedingRepository.findByOpenIdAndHabitationType(receiveMsg.getFromUserName(),HabitationTypeEnum.WS.getType());
        //饲养居住类型 1窝 2棚
        Integer habitationType = goodsInfo.getHabitationType();
        //饲养数量
        Integer habNum = feedingList.size();
        //剩余可饲养窝生数量
        Integer sywsNum=myPasture.getNestNum()-wslist.size();;
       //剩余可饲养棚生数量
        Integer sypsNum=myPasture.getShedNum()-pslist.size();
        Boolean syState=true;
        String pastureBag = getBag(receiveMsg,goodsName);
        if (habitationType== HabitationTypeEnum.WS.getType()){
            //窝生
            if (habNum>=myPasture.getNestNum()){
                if (sypsNum>0){
                    replyContent="饲养失败,窝已满,棚还有"+sypsNum+"个空余";
                    replyContent=replyContent.replace("{info}",replyContent).replace("{goods}",pastureBag);
                }else {
                    replyContent="饲养失败,窝已满,棚已满";
                }
                syState=false;
            }
        }else {
            //棚生
            if (habNum>=myPasture.getNestNum()){
            if (sywsNum>0){
                replyContent="饲养失败,棚已满,窝还有"+sywsNum+"个空余";
                replyContent=replyContent.replace("{info}",replyContent).replace("{goods}",pastureBag);
            }else {
                replyContent="饲养失败,棚已满,窝已满";
            }
            syState=false;
            }
        }
        //可饲养
        if (syState){
            //修改背包数量
            myBag.setNum(myBag.getNum()-1);
            if (myBag.getNum()==0){
                //删除数据
                Query query=  new Query().addCriteria(Criteria.where("goodsName").is(goodsName)).addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()));
                mongoTemplate.remove(query,MyBag.class);
            }else {
                myBagRepository.save(myBag);
            }
            PastureFeeding feeding  = new PastureFeeding();
            feeding.setType(PastureGrowUpType.YZQ.getType());
            feeding.setTypeName(PastureGrowUpType.YZQ.getName());
            feeding.setNestTypeName(PastureGrowUpType.CZQ.getName());
            feeding.setNextProduceTime((long) (goodsInfo.getCubPrice()*1000*60*60));
            //总时间
            Integer totalTime = goodsInfo.getCubStageTime()+goodsInfo.getGrowthPeriodTime()+goodsInfo.getProduceTotalTime();
            feeding.setEndTime((long) (totalTime*1000*60*60)+System.currentTimeMillis());
            feeding.setNextProduceTime((long) (goodsInfo.getCubStageTime()*1000*60*60)+System.currentTimeMillis());
            feeding.setOpenId(receiveMsg.getFromUserName());
            feeding.setHabitationType(habitationType);
            feeding.setGoodsName(goodsInfo.getGoodsName());
            feeding.setProductionStatus(0);
            feeding.setProduceTime((long) (goodsInfo.getProduceTime()*1000*60*60));
            feeding.setProduceTotalTime((long) (goodsInfo.getProduceTotalTime()*1000*60*60));
            feeding.setCubStageTime((long) (goodsInfo.getCubStageTime()*1000*60*60));
            feeding.setGrowthPeriodTime((long) (goodsInfo.getGrowthPeriodTime()*1000*60*60));
            feeding.setMucao(goodsInfo.getGrassConsumeNum());
            mongoTemplate.save(feeding);
            StringBuffer info =new StringBuffer();
            info.append("✅成功饲养1只"+goodsName+",");
            if (sywsNum<=1){
                //窝生
                info.append("窝已满,");
            }else {
                info.append("窝还有"+(sywsNum-1)+"个空余,");
            }
            if (sypsNum<=1){
                //窝生
                info.append("棚已满");
            }else {
                info.append("棚还有"+(sypsNum-1)+"个空余");
            }

            replyContent=replyContent.replace("{info}",info.toString()).replace("{goods}",pastureBag);
        }
       return replyContent;
    }

    /** 
    * @Description: 牧场商店
     * @param replyContent
     * * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/5/4 15:20
    */
    
    private String pastuerShop(String replyContent, ReceiveMsg receiveMsg) {
        //获取当前牧场等级
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        //未开启牧场，开启牧场操作
        if (myPasture==null){
            replyContent="您还未拥有牧场，请【pastureBaga href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=购买牧场\">购买牧场pastureBag/a>】,购买牧场将花费1000\uD83D\uDCB0金币";
            return replyContent;
        }
        //查询物品
        List<ShopGoods> shopGoods = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        Query query = new Query();
        query.addCriteria(Criteria.where("shopType").is(ShopTypeConstant.MC_SC));
        if (receiveMsg.getContent().equals("查看目前不能购买的幼仔")){
            query.addCriteria(Criteria.where("goodsLevel").gt(myPasture.getLevel()));
            shopGoods=mongoTemplate.find(query,ShopGoods.class);
            for (ShopGoods goods:shopGoods){
                buffer.append(goods.getGoodsName()+"("+goods.getRemark()+")\n");
            }
        }else {
            query.addCriteria(Criteria.where("goodsLevel").lte(myPasture.getLevel()));
            shopGoods=mongoTemplate.find(query,ShopGoods.class);
            String butStr = "<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=购买${goodsName}*1\">购买</a>";
            for (ShopGoods goods:shopGoods){
                buffer.append(goods.getGoodsName()+"("+goods.getRemark()+") "+butStr.replace("{goodsName}",goods.getGoodsName())+"\n");
            }
        }
        replyContent=replyContent.replace("{info}",buffer.toString());
        return replyContent;
    }

    /** 
    * @Description: 牧场背包
     * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/28 14:42
    */
    
    private String pastureBag(String replyContent, ReceiveMsg receiveMsg) {
        List<MyBag> myBag = myBagRepository.findByOpenIdAndType(receiveMsg.getFromUserName(),BagConstant.MC);
        StringBuffer buffer = new StringBuffer();
        String info ="暂无物品";
        if (myBag.size()>0){
            for (MyBag bag:myBag){
                String butStr = "<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=饲养${goodsName}\">饲养</a>";
                if (bag.getGoodsName().contains("罐头")){
                    buffer.append(bag.getGoodsName()+"x"+bag.getNum()+"\n");
                }else {
                    butStr=butStr.replace("{goodsName}",bag.getGoodsName());
                    buffer.append(bag.getGoodsName()+"x"+bag.getNum()+" "+butStr+"\n");
                }
            }
            info=buffer.toString();
        }
        replyContent=replyContent.replace("{info}",info);
        return replyContent;

    }

    /**
     * 饲养背包回显
     * @param receiveMsg
     * @return
     */
    private String getBag(ReceiveMsg receiveMsg,String goodsName) {
        List<MyBag> myBag = myBagRepository.findByOpenIdAndType(receiveMsg.getFromUserName(),BagConstant.MC);
        StringBuffer buffer = new StringBuffer();
        String info ="暂无物品";
        String content="";
        if (myBag.size()>0){
            for (MyBag bag:myBag){
                //数量回显处理
                Integer goodsNum=bag.getNum();
                if (bag.getGoodsName().equals(goodsName)){
                    goodsNum=goodsNum-1;
                    if (goodsNum==0){
                        continue;
                    }
                }
                String butStr = "<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=饲养${goodsName}\">饲养</a>";
                if (bag.getGoodsName().contains("罐头")){
                    buffer.append(bag.getGoodsName()+"x"+goodsNum+"\n");
                }else {
                    butStr=butStr.replace("{goodsName}",bag.getGoodsName());
                    buffer.append(bag.getGoodsName()+"x"+goodsNum+" "+butStr+"\n");
                }
            }
            info=buffer.toString();
        }
        content=info.toString();
        return content;

    }
    /** 
    * @Description: 购买牧场
     * @param replyContent
 * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/28 13:49
    */
    private String buyPasture(String replyContent, ReceiveMsg receiveMsg) {
        //判断是否拥有牧场
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        if (myPasture!=null){
            replyContent="购买失败,您已拥有牧场";
            return replyContent;
        }
        //购买牧场，消费金币，判断金币是否充足
        User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
        if (user.getJinbi()<1000){
            replyContent="购买失败,您的金币不足";
            return replyContent;
        }
        //初始化牧场
        initPasture(user,receiveMsg);
        return replyContent;
    }

    /**
     * 初始化牧场
     */
    private void initPasture( User user,ReceiveMsg receiveMsg) {
        //创建牧场
        MyPasture myPasture=new MyPasture();
        myPasture.setLevel(0);
        myPasture.setJingYan(0);
        myPasture.setNestLevel(1);
        myPasture.setNestNum(2);
        myPasture.setShedLevel(0);
        myPasture.setShedNum(0);
        myPasture.setOpenId(receiveMsg.getFromUserName());
        myPasture.setMucao(1000);
        myPastureRepository.save(myPasture);
        //更新用户金额
        user.setJinbi(user.getJinbi()-1000);
        userRepository.save(user);
        //恭喜您成功花费1000金币购买牧场，获得🐥鸡x5,🐇兔子x5,📦初级罐头x5,🌿牧草x200
        MyBag myBag = new MyBag(); myBag.setType(BagConstant.MC); myBag.setGoodsName("鸡"); myBag.setNum(5);
        myBag.setOpenId(receiveMsg.getFromUserName());mongoTemplate.save(myBag);
        myBag = new MyBag(); myBag.setType(BagConstant.MC); myBag.setGoodsName("兔子"); myBag.setNum(5);
        myBag.setOpenId(receiveMsg.getFromUserName());mongoTemplate.save(myBag);
        myBag = new MyBag(); myBag.setType(BagConstant.MC); myBag.setGoodsName("初级罐头"); myBag.setNum(5);
        myBag.setOpenId(receiveMsg.getFromUserName());mongoTemplate.save(myBag);
        //牧草，添加到农场仓库中
        MyWareHouse myWareHouse = myWareHouseRepository.findByOpenIdAndGoodsName(receiveMsg.getFromUserName(),"牧草");
        if (myWareHouse!=null){
            myWareHouse.setNum(myWareHouse.getNum()+200);
        }else {
            myWareHouse= new MyWareHouse();
            myWareHouse.setGoodsName("牧草");
            myWareHouse.setOpenId(receiveMsg.getFromUserName());
            myWareHouse.setType(WearHouseConstant.NC);
            myWareHouse.setNum(200);
        }
        mongoTemplate.save(myWareHouse);
    }

    /** 
    * @Description: 小窝牧场
     * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/28 10:19
    */
    
    private String pastureInfo(String replyContent, ReceiveMsg receiveMsg) {
        MyPasture myPasture = myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
        //未开启牧场，开启牧场操作
        if (myPasture==null){
            replyContent="您还未拥有牧场，请【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=购买牧场\">购买牧场</a>】,购买牧场将花费1000\uD83D\uDCB0金币";
            return replyContent;
        }
        User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
        //牧场动物数据
        String pastureAnimalInfo = getPastureAnimalInfo(receiveMsg);
        List<PastureFeeding> netList=pastureFeedingRepository.findByOpenIdAndHabitationType(receiveMsg.getFromUserName(),HabitationTypeEnum.WS.getType());
        List<PastureFeeding> shedList=pastureFeedingRepository.findByOpenIdAndHabitationType(receiveMsg.getFromUserName(),HabitationTypeEnum.PS.getType());
        //todo 每级升级所需经验为 N*200
        Integer level=myPasture.getLevel();
        replyContent= replyContent.replace("{lv}",level.toString())
                .replace("{jinbi}",user.getJinbi().toString())
                .replace("{jingyan}",myPasture.getJingYan().toString()+"/"+(level+1)*200)
                .replace("{wo}",netList.size()+"/"+myPasture.getNestNum().toString())
                .replace("{peng}",shedList.size()+"/"+myPasture.getShedNum().toString())
                .replace("{mucao}",myPasture.getMucao()+"/1000")
                .replace("{goods}",pastureAnimalInfo);
       return replyContent;
    }

    /**
     * 牧场动物状态查询
     * @param receiveMsg
     * @return
     */
    private String getPastureAnimalInfo(ReceiveMsg receiveMsg) {
        String info="您的牧场空空如也，去【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=牧场背包\">牧场背包</a>】饲养动物吧";
        StringBuffer buffer = new StringBuffer();
        List<PastureFeeding> feedingList = pastureFeedingRepository.findByOpenId(receiveMsg.getFromUserName());
        Query query = new Query();
        query.addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()));
        query.with(Sort.by(Sort.Direction.DESC,"type"));
        feedingList= mongoTemplate.find(query,PastureFeeding.class);
        if (feedingList.size()>0){
            int index=0;
            for (PastureFeeding feeding:feedingList){
                index=index+1;
                //时期判断
                //成长时间
                Long czTime= feeding.getCubStageTime()+feeding.getGrowthPeriodTime();
                Long scTime=feeding.getProduceTotalTime();
                //可生产
                if (feeding.getType() ==PastureGrowUpType.SCQ.getType()){
                    buffer.append(goodsContent(index,feeding,feeding.getType()));
                }else if (feeding.getType() == PastureGrowUpType.SHQ.getType()){
                    //可收获
                    buffer.append(goodsContent(index,feeding,feeding.getType()));
                }else {
                    //TODO 状态更新存在5秒的时差
                    if (feeding.getType()<=PastureGrowUpType.CZQ.getType()){
                        //幼崽期，成长期内可以喂养罐头
                        buffer.append(index+")"+feeding.getGoodsName()+":"+feeding.getTypeName()+"【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=喂罐头\">喂罐头</a>】\n");
                    }else {

                        buffer.append(index+")"+feeding.getGoodsName()+":"+feeding.getTypeName()+"\n");
                    }
                    long time =feeding.getEndTime()-System.currentTimeMillis();
                    if (time<feeding.getProduceTime()){
                        buffer.append("     "+ DateUtil.timeChange(feeding.getEndTime())+"后到"+PastureGrowUpType.SHQ.getName()+"\n");
                    }else {
                        buffer.append("     "+ DateUtil.timeChange(feeding.getNextProduceTime())+"后到"+feeding.getNestTypeName()+"\n");
                    }
                }
            }

            info=buffer.toString();
        }
        return info;
    }

    /**
     * 处理牧场动物回显文本
     * @return
     */
    public String goodsContent(int index,PastureFeeding feeding,Integer type){
        String content="";
        //可赶产
        if (type==PastureGrowUpType.SCQ.getType()){
            String doSome="【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=赶产${goodsName}\">赶产</a>】\n";
            doSome=doSome.replace("{goodsName}",feeding.getGoodsName());
            content=index+")"+feeding.getGoodsName()+":"+PastureGrowUpType.SCQ.getName()+doSome;
        }
        //可收获
        if (type==PastureGrowUpType.SHQ.getType()){
            String doSome="【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=收获${goodsName}\">收获</a>】\n";
            doSome=doSome.replace("{goodsName}",feeding.getGoodsName());
            content=index+")"+feeding.getGoodsName()+":"+PastureGrowUpType.SHQ.getName()+doSome;
        }

        return content;
    }
}
